   var search_delay_msecs = 450;
   var sms_limit = 160;
   var last_query = "";
   var any_change = false;
   var tty = "";
   var done_poll_msecs = 500;
   var dropdown = null;

   var content_delay_msecs = 700;
   var content_timer = null;

   // update check
   var version = "1.92";
   var updateURL = "";
   
   // get preference trying both instance-specific setting and
   // global value for widget.
   function getConfig(name) {
     var v = widget.preferenceForKey(widget.identifier + "-" + name);
     return v != undefined ? v : widget.preferenceForKey(name);
   }
   
   // store preference both specifically for widget and globally.
   function setConfig(name, value) {
     widget.setPreferenceForKey(value, widget.identifier + "-" + name);
     widget.setPreferenceForKey(value, name);
   }
   
   var req = null;
   function request(url, ondone) {
     var onstatechange = function() {
       if(req.readyState < 4) return;
       if(req.status == 200) ondone();
     };

	 if(window.XMLHttpRequest) {
       req = new XMLHttpRequest();
       req.onreadystatechange = onstatechange;
       req.open("GET", url, true);
       req.send(null);
       return true;
     } 

     if(window.ActiveXObject) {
       req = new ActiveXObject("Microsoft.XMLHTTP");
       if(req) {
         req.onreadystatechange = onstatechange;
         req.open("GET", url, true);
         req.send();
         return true;
       }
     }

     req = null;
     alert("Error creating XMLHTTPRequest object");
	 return false;
   }
   
   function updateCheckDone() {
   }

   function checkUpdates() {
   }
   
   function debug(msg) {
   }

   function populateDevices() {
   }
 
   function search() {
	   var query = dropdown.unselectedValue();

     // hide dropdown when input field empty
	 if(query == "") dropdown.hide();

     if(query != "" && (query.toLowerCase() != 
			 			   last_query.toLowerCase() || any_change)) {
	     last_query = query;
	     any_change = false;
       
		 var nums = smsPlugin.abSearch(query);
		
		 window.resizeTo(270, 219); // allow extra space for dropdown to the right.
		 dropdown.populate(nums);
     }
   }

   var search_timer = null;
   function delayedSearch() {
	 if(!dropdown) return;					   

     var q = dropdown.unselectedValue();
     if(q != "" && q.toLowerCase() != last_query.toLowerCase()) {
	   last_query = q;
	   any_change = true;
     }

     if(search_timer != null) clearTimeout(search_timer);
     search_timer = setTimeout(search, search_delay_msecs);
   }

function resetInfoText() {
  document.getElementById("backmsg").innerHTML = 
   "<br />O Hai.";
}

function setInfoText(msg) {
  if(msg.length == 0) resetInfoText();
  else document.getElementById("backmsg").innerText = msg;
}

function setInfoHTML(msg) {
  if(msg.length == 0) resetInfoText();
  else document.getElementById("backmsg").innerHTML = msg;
}

function loadText(name) {
   var value = getConfig(name);
   if (value) {
		document.getElementById(name + "Txt").value = value;
	}
}


function loadCheckbox(name) {
   var value = getConfig(name);
   if(value == undefined) value = false;
   document.getElementById(name + "Setting").checked = value;
}


function saveCheckbox(name) {
    var value = document.getElementById(name + "Setting").checked;
    setConfig(name, value);
}

function saveText(name) {
    var value = document.getElementById(name + "Txt").value;
    setConfig(name, value);
}


function load()
{
  setupParts();
  activateHiding('erasePhone', 'phonenum');
  activateHiding('eraseMessage', 'msg-content');
 
  var input = document.getElementById("phonenum");
  dropdown = mkDropDown(input, 'dropdown');
  tooltip = document.getElementById("tooltip");
    
  resetInfoText();

  loadCheckbox("search");
  loadText("url");
  loadText("user");
  loadText("pass");
  loadText("no");
  
  value = widget.preferenceForKey(widget.identifier + "-phonenum");
  if(value != undefined) {
	var e = document.getElementById("phonenum");
    e.value = value;
  }
  phoneChanged();
     
  value = widget.preferenceForKey(widget.identifier + "-content");
  if(value != undefined) {
    var e = document.getElementById("msg-content");
	e.value = value;
  }
  contentChanged();
}

function remove()
{
	// your widget has just been removed from the layer
	// remove any preferences as needed
	// widget.setPreferenceForKey(null, createInstancePreferenceKey("your-key"));
}


function hide()
{
	// your widget has just been hidden stop any timers to
	// prevent cpu usage
}

function show()
{
	// your widget has just been shown.  restart any timers
	// and adjust your interface as needed
  checkUpdates();

  // if backside was allready shown we update list of devices.
}

function showBack(event)
{
     window.resizeTo(206, 219); // remove extra space for dropdown to the right,
                                // it makes flip look really funky.

	// your widget needs to show the back

	var front = document.getElementById("front");
	var back = document.getElementById("back");

	if (window.widget)
		widget.prepareForTransition("ToBack");

	front.style.display="none";
	back.style.display="block";
	
	if (window.widget)
		setTimeout('widget.performTransition();', 0);
}

function showFront(event)
{
  // store checkbox settings
  saveCheckbox("search");
  saveText("url");
  saveText("user");
  saveText("pass");
  saveText("no");

	// your widget needs to show the front
	var front = document.getElementById("front");
	var back = document.getElementById("back");

	if (window.widget) widget.prepareForTransition("ToFront");
	front.style.display="block";
	back.style.display="none";
	if(window.widget) setTimeout('widget.performTransition();', 0);
}

if (window.widget)
{
	widget.onremove = remove;
	widget.onhide = hide;
	widget.onshow = show;
}

function set_enabled(enabled) {
  document.getElementById("msg-content").disabled = !enabled;
  document.getElementById("phonenum").disabled = !enabled;

  document.getElementById("button").src = enabled ? "Images/send.png" : "Images/send-inactive.png";
  document.getElementById("clear").src = enabled ? "Images/clear.png" : "Images/clear-inactive.png";
}

function countOccurrence(haystack, needle) {
  var num = 0, pos = -1;
  for(;;) {
    pos = haystack.indexOf(needle, 1 + pos);
    if(pos < 0) return num;
    num += 1;    
  }
}

var last_phone = "";
var sms_cmd = null;
function setStatus(msg) {
  var problem = msg.length > 0;       
  if(!problem) msg = "Message to " + last_phone + " sent successfully.";
  else msg = "Unable to send message:\n" + msg;

  var bt = document.getElementById("bt");
  bt.my_tooltip = msg;
  bt.src = "Images/" + (problem ? "red" : "green") + ".png";
  set_enabled(true);
}
function resetStatus() {
  var bt = document.getElementById("bt");
  bt.my_tooltip = "";
  bt.src = "Images/black.png";
}

// remove name information and fix characters.
function filterPhone(phone) {
  // remove name info
  var pos = phone.indexOf("\xa0(");
  if(pos >= 0) phone = phone.substring(0, pos);

  // remove spaces, dots, dashes and remaining parenthesis
  phone = phone.replace(/[ ()\-\.\\\/]/g, "");
  
  return phone;
}

function getSMSC() {
	var smsc = getConfig(tty + "-smsc");
	if(smsc == undefined) smsc = "";
	return smsc;
}

function handleSendError(errmsg) {
}

function clearSMSC() {
}

function storeSMSC() {
}

function sendSMS(evt) 
{
  var phone = document.getElementById("phonenum");
  var content = escape(document.getElementById("msg-content").value);

  // ignore sends when phone or content is empty.
  if(phone.value == "" || content.value == "") return;

  var phonenum = phone.value;
  phone.value = phonenum; // unselect text
  phonenum = last_phone = filterPhone(phonenum);

  // turn off content-change action, when not needed
  if(content_timer != null) clearTimeout(content_timer);
  
  set_enabled(false);
  var bt = document.getElementById("bt");
  bt.src = "Images/blue.png";
  bt.my_tooltip = "";

  dropdown.populate(new Array());

  //smsPlugin.send(decorateDev(tty), getSMSC(), phonenum, content, receipt);
  url = document.getElementById("urlTxt").value
  user = urlencode(document.getElementById("userTxt").value)
  pass = urlencode(document.getElementById("passTxt").value)
  no = urlencode(document.getElementById("noTxt").value)
  query = "?username=" + user + "&password=" + pass + "&from=" + no + "&to=" + urlencode(phonenum) + "&text="+ content;
  alert(url + query)
    
var feedURL = url + query;
var onloadHandler = function() { checkSendDone(xmlRequest); };	
var xmlRequest = new XMLHttpRequest();

xmlRequest.onload = onloadHandler;
xmlRequest.open("GET", feedURL);
xmlRequest.setRequestHeader("Cache-Control", "no-cache");
xmlRequest.send(null);  
}

function sendDone(errmsg) {
	//handleSendError(msg);
	setStatus(errmsg);
	document.getElementById("msg").innerText = errmsg;
}

function checkSendDone(xmlRequest) {

	if (xmlRequest.status == 200) {
		
	
		var root = xmlRequest.responseText.match(/<description>(.*?)<\/description>/);
		sendDone(root[1]);
	}
	else {
		alert("Error fetching data: HTTP status " + xmlRequest.status);
	}
}

function keyPress(evt) {
  if(evt.ctrlKey && evt.charCode == 19) {
    sendSMS(evt);
    return false;
  } 
  return true;
}

function eraseContent() {
	document.getElementById("msg-content").value = "";
	contentChanged();
	document.getElementById("msg-content").value = "";
}

function ClearAll(evt) {
	document.getElementById("phonenum").value = "";
	document.getElementById("msg-content").value = "";
	phoneChanged();
	contentChanged();
	document.getElementById("phonenum").value = "";
	document.getElementById("msg-content").value = "";	
}

function delayedContentChanged() {
  var value = document.getElementById("msg-content").value;
  var chars = value.length;
  var num = smsPlugin.smsCount(value);

  var msg = chars + "/" + num;
  var e = document.getElementById("msg");
  if(chars > 0) {
  	e.innerText = msg;
    var characters = " character" + (chars == 1 ? "" : "s");
    var messages = " message" + (num == 1 ? "" : "s");
  	e.my_tooltip = "" + chars + characters + " in " + num + messages + ".";
  } else {
	e.innerText = e.my_tooltip = "";
  }

  widget.setPreferenceForKey(value, widget.identifier + "-content");
	
}

function contentChanged(evt) 
{
  resetStatus();
  somethingChanged();	
	
  var value = document.getElementById("msg-content").value;
  if(value.length >= sms_limit) {
    value = value.substring(0, sms_limit);
    document.getElementById("msg-content").value = value;
  }
  
  document.getElementById("msg").innerText = "";
  if(content_timer != null) clearTimeout(content_timer);
  content_timer = setTimeout(delayedContentChanged, content_delay_msecs);
  return true;
}

// return array of words, where str is delimited by space and
// regular punctuation.
function getWords(str) {
  var tokens = str.split(/[ \t\n\r,.;:"'"]/);
  var words = new Array();
  for(var i = 0; i < tokens.length; ++i) {
    if(tokens[i].length > 0) {
      words[words.length] = tokens[i];
    }
  }
  return words;
}

function buildPhoneInfo(str) {
}

function testSerialPort(dev) {
}

function checkTestDone() {
}

function testDone(msg) {
}

function backEnabled(enabled) {
  document.getElementById("done").object.setEnabled(enabled);
  document.getElementById("searchSetting").disabled = !enabled;	
}

function terminalChanged(event) {
}

function storePhone(evt) {
   var p = document.getElementById("phonenum");
   widget.setPreferenceForKey(p.value, widget.identifier + "-phonenum");
   return false;
}

function somethingChanged() {
  var p = document.getElementById("phonenum");
  var c = document.getElementById("msg-content");
  var enabled = p.value.length > 0 && c.value.length > 0;
  document.getElementById("button").src = enabled ? "Images/send.png" : "Images/send-inactive.png";	

  var enabled = p.value.length > 0 || c.value.length > 0;
  document.getElementById("clear").src = enabled ? "Images/clear.png" : "Images/clear-inactive.png";
}

function phoneChanged(evt) 
{
  resetStatus();  
  somethingChanged();

  if(document.getElementById("searchSetting").checked) delayedSearch();

  return storePhone(evt);
}

function doUpdate(event) 
{
}


function urlencode(str) {
str = escape(str);
str = str.replace('+', '%2B');
str = str.replace('%20', '+');
str = str.replace('*', '%2A');
str = str.replace('/', '%2F');
str = str.replace('@', '%40');
return str;
}

function TestAll(event) 
{
	// Insert Code Here
}
